import axios from 'axios'
import { setCookie, getCookie, delCookie } from '../../assets/js/cookie.js'

const state = {
    isLogin: false, // 是否登录
    promptMessage: '',     // 登录失败提示语
    myinfo: {
        id: '',
        joined: '',
        mobile: '',
        expired: '',
        level: '',
        money: '0',
        sms: [],
        sysnote: []
    }
}

const mutations = {

    login(state, payload) {
        state.isLogin = true,
        state.myinfo = payload.res
    },
    loginOut(state) {
        state.isLogin = false,
        state.myinfo = {
            id: '',
            joined: '',
            mobile: '',
            expired: '',
            level: '',
            money: '0',
            sms: [],
            sysnote: []
        }
    },
    sync(state) {
        state.isLogin = true,
        state.myinfo = JSON.parse(getCookie('user_info'))
        console.log(state.myinfo)
    }
}

const actions = {
    login({commit}, param) {
        axios({
            method: 'post',
            url: 'http://api.fxnn.net/login/on',
            data: param.data
        })
        .then(function(res) {
            console.log(res)
            if(res.data.success) {
                console.log("登录成功")
                commit({
                    type: 'login',
                    res: res.data
                })
                // 保存seccsion
                setCookie('user_id',res.data.id,3)
                setCookie('login_key',res.data.login_key, 3)
                setCookie('user_info',JSON.stringify(res.data),3)
                // 登录成功后，弹出“登录成功”， 1.2秒后跳转到 home 页面
                param._this.$toast("登录成功")
                setTimeout(function(){
                    param._this.$router.push('/home')
                },1200)
                
            } else {
                console.log("登录失败")
            }
            
        })
        .catch(function (err) {
            console.log(err)
        })
    },
    loginOut({commit}) {
        delCookie('user_id')
        delCookie('login_key')
        delCookie('user_info')

        console.log("退出登录")

        commit({type: 'loginOut'})
    },
    // 刷新页面时，同步cookie 和 vuex 的数据
    sync({commit}) {
        if(getCookie('login_key')) {
            commit({
                type: 'sync'
            })
        }
    }
}

export default {
    state,
    mutations,
    actions
}